//
//  YZNoteInputView.m
//  VET
//
//  Created by 刘文靖 on 2018/7/12.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZNoteInputView.h"
#import "YZPhotoCell.h"
#import "YZWorkNoteModel.h"
#import <CALayer+YYWebImage.h>
#import "YZAudioRecordVC.h"
#import <UIControl+YYAdd.h>
#import "YZLineView.h"
#import "YZNoteAudioDisplayBtn.h"
@interface YZNoteInputView()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic, strong) UICollectionView *collectionView;
@property (strong, nonatomic) UICollectionViewFlowLayout *layout;
@property (nonatomic, strong) UIView *bottomToolView;
@property (nonatomic, strong) YZNoteAudioDisplayBtn *auidioView;
@property (nonatomic, assign) BOOL isMedia;
@end

@implementation YZNoteInputView
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
    }
    return self;
}


- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self setupUI];
    }
    return self;
}

- (void)setupUI{
    self.backgroundColor = [UIColor whiteColor];
    ///文本输入框
    self.notePics = [NSMutableArray array];
    self.textView = [[YYTextView alloc] init];
    self.textView.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
    [self addSubview:self.textView];
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.offset(24);
        make.right.offset(-24);
        make.height.mas_equalTo(136);
    }];
    //底部拍摄工具条
    self.bottomToolView = [[UIView alloc] init];
    [self addSubview:self.bottomToolView];
    self.bottomToolView.layer.cornerRadius = 4;
    self.bottomToolView.layer.borderWidth = 1;
    self.bottomToolView.layer.borderColor = kColorWithHexAlpha(0xD9D9D9, .5).CGColor;
    [self.bottomToolView setLayerShadow:kColorWithHexAlpha(0xD9D9D9,0.65) offset:CGSizeMake(0, 5) radius:4];
    [self.bottomToolView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(24);
        make.bottom.offset(-18);
        make.right.offset(-24);
        make.height.mas_equalTo(73);
    }];
    
    YZLineView *lineView = [[YZLineView alloc] init];
    [self addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.centerX.offset(0);
        make.left.offset(24);
        make.height.offset(.5);
    }];
    
    UIColor *titleColoer = kColorWithHex(0x434343);
    UIFont *titleFont = [UIFont fontWithName:@"PingFangSC-Semibold" size:16];
    
    UIButton *audioBtn = [[UIButton alloc] init];
    [audioBtn setImage:[UIImage imageNamed:@"ico_voice_biji"] forState:UIControlStateNormal];
    [audioBtn setTitle:@"语音" forState:UIControlStateNormal];
    [audioBtn setBackgroundColor:kColorWithHex(0xffffff)];
    [audioBtn setTitleColor:titleColoer forState:UIControlStateNormal];
    audioBtn.titleLabel.font = titleFont;
    [self.bottomToolView addSubview:audioBtn];
    [audioBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.top.offset(0);
    }];
    
    UIButton *imageBtn = [[UIButton alloc] init];
    [imageBtn setImage:[UIImage imageNamed:@"ico_album_biji"] forState:UIControlStateNormal];
    [imageBtn setTitle:@"图片" forState:UIControlStateNormal];
    [imageBtn setBackgroundColor:kColorWithHex(0xffffff)];
    [imageBtn setTitleColor:titleColoer forState:UIControlStateNormal];
    imageBtn.titleLabel.font = titleFont;
    [self.bottomToolView addSubview:imageBtn];
    [imageBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.top.width.mas_equalTo(audioBtn);
        make.left.mas_equalTo(audioBtn.mas_right);
    }];
    
    UIButton *videoBtn = [[UIButton alloc] init];
    [videoBtn setImage:[UIImage imageNamed:@"ico_video_biji"] forState:UIControlStateNormal];
    videoBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 6, 0, 0);
    [videoBtn setBackgroundColor:kColorWithHex(0xffffff)];
    [videoBtn setTitle:@"短视频" forState:UIControlStateNormal];
    [videoBtn setTitleColor:titleColoer forState:UIControlStateNormal];
    videoBtn.titleLabel.font = titleFont;
    [self.bottomToolView addSubview:videoBtn];
    [videoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.top.width.mas_equalTo(audioBtn);
        make.left.mas_equalTo(imageBtn.mas_right);
        make.right.offset(0);
    }];
    
    //图片显示CollectionView
    [self configCollectionView];
    
    @weakify(self)
    [audioBtn addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
        @strongify(self)
        self.isMedia = YES;
        if (self.delegate && [self.delegate respondsToSelector:@selector(audioBtnDidClick:)]){
            [self.delegate audioBtnDidClick:self];
        }
    }];
    
    [imageBtn addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
        @strongify(self)
        self.isMedia = NO;
        if (self.delegate && [self.delegate respondsToSelector:@selector(imageBtnDidClick:)]){
            [self.delegate imageBtnDidClick:self];
        }
    }];
    [videoBtn addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
        @strongify(self)
        self.isMedia = YES;
        if (self.delegate && [self.delegate respondsToSelector:@selector(videoBtnDidClick:)]){
            [self.delegate videoBtnDidClick:self];
        }
    }];
}

- (void)configCollectionView {
    // 如不需要长按排序效果，将LxGridViewFlowLayout类改成UICollectionViewFlowLayout即可
    _layout = [[UICollectionViewFlowLayout alloc] init];
    _layout.itemSize = CGSizeMake(itemWH, itemWH);
    _layout.minimumInteritemSpacing = margin;
    _layout.minimumLineSpacing = margin;
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_layout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [self addSubview:_collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.textView);
        make.top.mas_equalTo(self.textView.mas_bottom).offset(24);
        make.bottom.mas_equalTo(self.bottomToolView.mas_top);
    }];
    [self.collectionView registerClass:[YZPhotoCell class] forCellWithReuseIdentifier:@"YZPhotoCell"];
}


- (void)showAudioViewWithAudioUrl:(NSString *)audioUrl timeInterval:(NSInteger)timeInterval{
    self.bottomToolView.hidden = YES;
    if (self.auidioView) {
        self.auidioView.audioUrl = audioUrl;
        self.auidioView.totalTimeInterval = timeInterval;
        self.auidioView.hidden = NO;
    }else{
        self.auidioView = [[YZNoteAudioDisplayBtn alloc] initWithDisplayType:YZNoteAudioDisplayCreateNote audioUrl:audioUrl];
        self.auidioView.totalTimeInterval = timeInterval;
        [self addSubview:self.auidioView];
        [self.auidioView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(self.bottomToolView);
        }];
        
        UIButton *deleteBtn = [[UIButton alloc] init];
        [deleteBtn setBackgroundImage:[UIImage imageNamed:@"ico_inputdel"] forState:UIControlStateNormal];
        [_auidioView addSubview:deleteBtn];
        [deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.offset(0);
            make.right.offset(-10);
        }];
        @weakify(self)
        [[deleteBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self)
            self.auidioView.hidden = YES;
            self.bottomToolView.hidden = NO;
            if (self.delegate && [self.delegate respondsToSelector:@selector(audioDeleteDidClick:)]) {
                [self.delegate audioDeleteDidClick:self];
            }
        }];
    }
}

#pragma mark - setter
- (void)setPlaceHolder:(NSString *)placeHolder{
    _placeHolder = placeHolder;
    self.textView.placeholderFont = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
    self.textView.placeholderText = placeHolder;
}

- (void)setNote:(YZWorkNoteModel *)note{
    _note = note;
    self.textView.text = note.noteText;
    if (note.attachType == YZWorkNoteAttachTypeAudio) {
        [self showAudioViewWithAudioUrl:note.attachmentList.firstObject.attachmentUrl timeInterval:note.attachmentList.firstObject.mediaTime];
    }else{
        self.selectedPhotos = note.attachmentList;
    }
    
    _isMedia = note.attachType;
}

- (void)setSelectedPhotos:(NSArray *)selectedPhotos{
    if(!selectedPhotos.count){
        [self.bottomToolView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(73);
        }];
        self.bottomToolView.hidden = NO;
    }else if (!self.bottomToolView.hidden){
        [self.bottomToolView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(0);
        }];
        self.bottomToolView.hidden = YES;
    }
    _selectedPhotos = selectedPhotos;
    [self.notePics removeAllObjects];
    [self.collectionView reloadData];
}

#pragma mark - UICollectionView

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (_isMedia) {
        return _selectedPhotos.count;
    }
    return (_selectedPhotos.count > 0 && _selectedPhotos.count < 9)?_selectedPhotos.count + 1: _selectedPhotos.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    YZPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"YZPhotoCell" forIndexPath:indexPath];
    cell.videoImageView.hidden = !self.isMedia;
    if (indexPath.item == _selectedPhotos.count) {
        cell.imageView.contentMode = UIViewContentModeScaleAspectFill;
        cell.imageView.layer.contentsRect = CGRectMake(0, 0, 1, 1);
        cell.imageView.layer.contents = (__bridge id _Nullable)[UIImage imageNamed:@"ico_addphoto"].CGImage;
    } else {
        id asset = _selectedPhotos[indexPath.item];
        if ([asset isKindOfClass:[UIImage class]]){
            UIImage *image = _selectedPhotos[indexPath.item];
            [self.notePics addObject:image];
            int width = image.size.width;
            int height = image.size.height;
            CGFloat scale = (height / width);
            if (scale < 0.99 || isnan(scale)) { // 宽图把左右两边裁掉
                cell.imageView.contentMode = UIViewContentModeScaleAspectFill;
                cell.imageView.layer.contentsRect = CGRectMake(0, 0, 1, 1);
            } else { // 高图只保留顶部
                cell.imageView.contentMode = UIViewContentModeScaleToFill;
                cell.imageView.layer.contentsRect = CGRectMake(0, 0, 1, (float)width / height);
            }
            cell.imageView.layer.contents = (__bridge id _Nullable)image.CGImage;
            //cell.asset = _selectedAssets[indexPath.item];
        }else{
            NSURL *imageURL = [_selectedPhotos[indexPath.item] isKindOfClass:[YZAttachmentModel class]]?[_selectedPhotos[indexPath.item] url]:_selectedPhotos[indexPath.item];
            @weakify(cell)
            [cell.imageView.layer setImageWithURL:imageURL
                                      placeholder:nil
                                          options:YYWebImageOptionAvoidSetImage
                                       completion:^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) {
                                           @strongify(cell);
                                           if (!cell) return;
                                           if (image && stage == YYWebImageStageFinished) {
                                               [self.notePics addObject:(UIImage*)image];
                                               int width = image.size.width;
                                               int height = image.size.height;
                                               CGFloat scale = (height / width);
                                               if (scale < 0.99 || isnan(scale)) { // 宽图把左右两边裁掉
                                                   cell.imageView.contentMode = UIViewContentModeScaleAspectFill;
                                                   cell.imageView.layer.contentsRect = CGRectMake(0, 0, 1, 1);
                                               } else { // 高图只保留顶部
                                                   cell.imageView.contentMode = UIViewContentModeScaleToFill;
                                                   cell.imageView.layer.contentsRect = CGRectMake(0, 0, 1, (float)width / height);
                                               }
                                               cell.imageView.layer.contents =  (__bridge id _Nullable)image.CGImage;
                                               if (from != YYWebImageFromMemoryCacheFast) {
                                                   CATransition *transition = [CATransition animation];
                                                   transition.duration = 0.15;
                                                   transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
                                                   transition.type = kCATransitionFade;
                                                   [cell.imageView.layer addAnimation:transition forKey:@"contents"];
                                               }
                                           }
                                       }];
        }
        
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.item == _selectedPhotos.count) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(imageBtnDidClick:)]){
            [self.delegate imageBtnDidClick:self];
        }
    } else { // preview photos or video / 预览照片或者视频
        if (self.delegate && [self.delegate respondsToSelector:@selector(preViewImage:)]){
            [self.delegate preViewImage:indexPath.item];
        }
    }
}

- (void)dealloc{
    [self.auidioView stopPlay];
}

@end
